/****************
 *@description:  商城订单列表   storeBackManage/orderManage/mallOrder
 *@author: Xhd
 *@API: 贺义龙
 *@date: 2023-11-13 09:44:38
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import { Tabs, Modal } from "antd";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import TheImage from "@/components/TheImage";
import { apiGetShopOrderInfoPage, apiStoreInfoList, apiGetShopOrderInfoList } from '@/request/orderManagement';
import store from "@/store/store";
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate';
import { exportSheetTable } from '@/utils/exportTable.js'

const { TabPane } = Tabs

class StoreBackMallOrder extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef()
    this.state = {
      searchOption: [
        { field: 'orderCode', label: '订单编号', placeholder: '请输入订单编号', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'time', label: '下单时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
        { field: 'activityTypeCode', label: '订单类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '全部', value: '', }, { label: '普通订单', value: '0' }, { label: '砍价订单', value: '1' }, { label: '拼团订单', value: '2' }, { label: '奖品订单', value: '3' }], defaultValue: '' },
        { field: 'memberId', label: '用户ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'memberPhone', label: '收货手机号', placeholder: '请输入', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
        { field: 'storeId', label: '所属商家', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [], txt: 'storeName', value: 'storeId', api: apiStoreInfoList, params: {}, },
        { field: 'goodsQuery', label: '商品ID/名称', placeholder: '支持模糊查询', required: false, rules: [], type: 'Input', defaultValue: '' },
      ],
      queryForm: {},
      tabData: [
        { key: "", tab: '全部' },
        { key: "3", tab: '待付款' },
        { key: "6", tab: '待分享' },
        { key: "4", tab: '待发货' },
        { key: "5", tab: '待收货' },
        { key: "9", tab: '交易成功' },
        { key: "0", tab: '交易关闭' },
      ],
      orderState: "",
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0
    }
  }

  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'mallorder') {
      let { pageNo, pageSize, orderState } = searchParams
      this.setState({
        orderState,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData(queryForm)
      })
    } else {
      this.getData()
    }
  }
  //获取数据
  getData = async (values) => {
    const { queryForm, orderState, pageData } = this.state

    if (values && !_.isEmpty(values.time)) {
      values.createTimeStart = getDateTime3(values.time[0]) + " 00:00:00"
      values.createTimeEnd = getDateTime3(values.time[1]) + " 23:59:59"
      delete (values.time)
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        ...pageData, orderState, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'mallorder',
          ...params
        }
      })
      let res = await apiGetShopOrderInfoPage({ orderState, ...params.queryForm, ...pageData })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount
        })
      }
    })
  }
  //搜索
  onFormSearch = (values) => {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
    }, () => {
      this.getData(values)
    })
  }
  //重置
  onReset = () => {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  //tab切换
  changeKey = (key) => {
    this.setState({
      orderState: key,
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData()
    })
  }
  //翻页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => {
      this.getData()
    })
  }
  //售后详情
  toOrderSalesDetail = (e) => {
    this.props.history.push(`/storeBackManage/orderManage/afterSaleOrder/detail/${e}`)
  }
  //查看订单
  toDetail = (e) => {
    this.props.history.push(`/storeBackManage/orderManage/mallOrder/detail/${e}`)
  }
  //导出
  toExport = async () => {
    const { queryForm, orderState } = this.state
    if (!queryForm || Object.keys(queryForm).length === 0) {
      Modal.warning({
        title: "提醒",
        content: "请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。",
        okText: "我知道了",
        onOk: () => { }
      })
      return
    }
    let res = await apiGetShopOrderInfoList({ ...queryForm, orderState })
    if (res.code === 0 && res.data) {
      const th_arr = [
        {
          title: '商城订单列表',
          prop: '',
          children: [
            {
              title: '订单编号',
              prop: 'orderCode',
            },
            {
              title: '所属商户',
              prop: 'storeName',
            },
            {
              title: '买家昵称',
              prop: 'buyMemberName',
            },
            {
              title: '用户手机号',
              prop: 'orderMemberPhone',
            },
            {
              title: '支付方式',
              prop: 'payWay',
            },
            {
              title: '收货人',
              prop: 'memberName',
            },
            {
              title: '收货人联系方式',
              prop: 'memberPhone',
            },
            {
              title: '收货地址',
              prop: 'memberAddress',
            },
            {
              title: '订单类型',
              prop: 'activityTypeCode',

            },
            {
              title: '订单金额（元）',
              prop: 'orderTotalPrice',
              valueType: 'number'
            },
            {
              title: '实付金额（元）',
              prop: 'orderPayPrice',
              valueType: 'number'
            },
            {
              title: '订单时间',
              prop: 'createTime',
            },
            {
              title: '订单状态',
              prop: 'orderState',
            },
          ]
        },

      ]
      let tb_arr = []
      res.data.forEach(item => {
        tb_arr.push({
          orderCode: item.orderCode || '/',
          storeName: item.storeName || '/',
          buyMemberName: item.buyMemberName || '/',
          orderMemberPhone: item.orderMemberPhone || '/',
          payWay: item.payWay === "Alipay" ? "支付宝" : item.payWay === "WeChat" ? "微信" : item.payWay === "UnionPay" ? "银联" : item.payWay === "YsPay" ? "银行卡" : '/',
          memberName: item.memberName || '/',
          memberPhone: item.memberPhone || '/',
          memberAddress: item.memberAddress || '/',
          activityTypeCode: item.activityTypeCode == 0 ? '普通订单' : '砍价订单',
          orderTotalPrice: Number(item.orderTotalPrice / 100).toFixed(2) || '/',
          orderPayPrice: Number(item.orderPayPrice / 100).toFixed(2) || '/',
          createTime: item.createTime || '/',
          orderState: item.orderState === '3' ? "待付款" : item.orderState === '4' ? "待发货" : item.orderState === '5' ? "待收货" : item.orderState === "6" ? "待分享" : item.orderState === '9' ? "交易成功" : item.orderState === '0' ? "交易关闭" : ""
        })
      })
      exportSheetTable({ fileName: `商城订单${orderState === '3' ? "待付款" : orderState === '4' ? "待发货" : orderState === '5' ? "待收货" : orderState === "6" ? "待分享" : orderState === '9' ? "交易成功" : orderState === '0' ? "交易关闭" : ""}`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
    }
  }
  transOrderType = (type) => {
      switch (type) {
          case 0:
              return '普通订单'
          case 1:
              return '砍价订单'
          case 2:
              return '拼团订单'
          case 3:
              return '奖品订单'
          default:
              return ''
      }
  }
  render() {
    const { searchOption, tabData, dataSource, pageData, total, orderState } = this.state
    return (
      <div className='p-layout-box'>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton haspermi={['storeBack:mallOrder:export']} size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
        </TheQueryForm>
        <Tabs onChange={this.changeKey} activeKey={orderState} >
          {tabData.map(v => {
            return <TabPane key={v.key} tab={v.tab}>
              <table style={{ width: "100%", lineHeight: "40px", overflowX: "scroll" }}  >
                <thead style={{ textAlign: "center", backgroundColor: "#ddd" }}>
                  <td colSpan={2} style={{ width: "500px" }}>商品</td>
                  <td>单价（元）</td>
                  <td>数量</td>
                  <td>售后</td>
                  <td>实付金额（元）</td>
                  <td>订单状态</td>
                  <td>操作</td>
                </thead>
                <div style={{ height: 10 }}></div>
                {dataSource && dataSource.map((v, i) => {
                  let row = v.orderDetailList ? v.orderDetailList.length : 0
                  let orderState = ""
                  switch (v.orderState) {
                    case "3":
                      orderState = "待付款"
                      break;
                    case "4":
                      orderState = "待发货"
                      break;
                    case "5":
                      orderState = "待收货"
                      break;
                    case "6":
                      orderState = "待分享"
                      break;
                    case "9":
                      orderState = "交易成功"
                      break;
                    case "0":
                      orderState = "交易关闭"
                      break;
                    default:
                      break;
                  }
                  return <tbody>
                    <tr style={{ backgroundColor: "#ddd" }}>
                      <td colSpan={9} >
                        <div style={{ display: "flex" }}>
                          <div>订单号：{v.orderCode}</div>
                          <div style={{ width: "40px" }}></div>
                          <div>下单时间：{v.createTime}</div>
                          <div style={{ width: "40px" }}></div>
                          <div>{v.storeChannel === 1 ? <span style={{ backgroundColor: "red", borderRadius: "3px", color: "white", paddingLeft: "3px", paddingRight: "3px", marginRight: "5px" }}>自营</span> : null}{v.storeName}</div>
                          <div style={{ width: "40px" }}></div>
                          {/*<div>{v.activityTypeCode === 0 ? "普通订单" : v.activityTypeCode === 1 ? "砍价订单" : "拼团订单"}</div>*/}
                          <div>{this.transOrderType(v.activityTypeCode)}</div>
                        </div>
                      </td>
                    </tr>
                    {v.orderDetailList ? v.orderDetailList.map((item, index) => {
                      let salesStatus = ""
                      switch (item.salesStatus) {
                        // case "1":
                        //   salesStatus = "退款中"
                        //   break;
                        // case "2":
                        //   salesStatus = "退款中，平台已同意，待寄回商品"
                        //   break;
                        // case "3":
                        //   salesStatus = "退款中，商品已寄回，待平台确认"
                        //   break;
                        // case "4":
                        //   salesStatus = "退款失败"
                        //   break;
                        // case "9":
                        //   salesStatus = "退款成功"
                        //   break;
                        // case "0":
                        //   salesStatus = "退款关闭"
                        //   break;
                        case "1": case "2": case "3":
                          salesStatus = "售后中"
                          break
                        case "4": case "9": case "0":
                          salesStatus = "售后详情"
                          break
                        default:
                          salesStatus = "-"
                          break;
                      }
                      let backgroundColor = salesStatus === "-" ? "" : "#F08080"
                      if (index === 0) {
                        return <tr style={{ textAlign: "center", }}>
                          <td width={100} style={{ paddingTop: "10px", backgroundColor }}><TheImage src={item.goodsImage} width={80} /></td>
                          <td style={{ width: "400px", backgroundColor }} >{item.goodsName}<br />{item.goodsSkuJson ? JSON.parse(item.goodsSkuJson).skuAttribute?.map((e) => {
                            return e.key + ":" + e.value
                          }) : null}</td>
                          <td style={{backgroundColor}}><React.$Price price={item.orderPrice} /></td>
                          <td style={{backgroundColor}}>{"x" + item.orderGoodsCount}</td>
                          <td style={{backgroundColor}}>{salesStatus === "-" ? salesStatus : <TheButton type="link" haspermi={['storeBack:mallOrder:afterSale']} onClick={() => this.toOrderSalesDetail(item.shopSalesReturnId)}>{salesStatus}</TheButton>}</td>
                          <td rowSpan={row}><React.$Price price={v.orderPayPrice} /><br />（含运费：<React.$Price price={v.freight} />）</td>
                          <td rowSpan={row}>{orderState}</td>
                          <td rowSpan={row}>
                            <TheButton type="link" haspermi={['storeBack:mallOrder:detail']} onClick={() => this.toDetail(v.shopOrderId)} >查看订单</TheButton>
                          </td>
                        </tr>
                      }
                      return <tr style={{ textAlign: "center", backgroundColor}}>
                        <td width={100} style={{ paddingTop: "10px" }}><TheImage src={item.goodsImage} width={80} /></td>
                        <td>
                          <div style={{overflow:"hidden"}}>
                            {item.goodsName}
                          </div>
                          {JSON.parse(item.goodsSkuJson).skuAttribute.map((e) => {
                            return e.key + ":" + e.value
                          })}
                        </td>
                        <td><React.$Price price={item.orderPrice} /></td>
                        <td>{"x" + item.orderGoodsCount}</td>
                        <td>{salesStatus === "-" ? salesStatus : <TheButton type="link" haspermi={['storeBack:mallOrder:afterSale']} onClick={() => this.toOrderSalesDetail(item.shopSalesReturnId)}>{salesStatus}</TheButton>}</td>
                      </tr>
                    }) : <div>订单数据异常</div>}
                  </tbody>
                })}
              </table>
              <ThePagination
                pageNo={pageData.pageNo}
                pageSize={pageData.pageSize}
                total={total}
                pageChange={this.pageChange}
              ></ThePagination>
            </TabPane>
          })}
        </Tabs>
      </div>
    )
  }

}

export default StoreBackMallOrder
